package manage.commons.utils;

/**
 * 
 * Description：获取表名工具类
 * 
 * @since：2012-8-17 下午09:50:38
 * @author dongji
 * 
 */
public class TableNameUtil {
	private static final String TABLE_SEPARATE = "_";
	private static final TABLE_RULES DEFAULT_TABLE_NAME_RULES = TABLE_RULES.SIMPLE_RULE;

	/**
	 * 表名规则
	 */
	private static enum TABLE_RULES {
		SIMPLE_RULE, SEPARATE_RULE
	}

	public static <T> String getTableName(Class<T> clazz) {
		return getTableName(clazz, DEFAULT_TABLE_NAME_RULES);
	}

	public static <T> String getTableName(Class<T> clazz, TABLE_RULES rule) {
		String className = clazz.getSimpleName();
		if (rule == TABLE_RULES.SIMPLE_RULE) {
			return "`" + className + "`";
		}
		int[] pos = new int[className.length()];
		int j = 0;
		for (int i = 0; i < className.length(); i++) {
			if (className.charAt(i) >= 'A' && className.charAt(i) <= 'Z') {
				pos[j] = i;
				j++;
			}
		}
		if (j == 1) {
			return "`" + className + "`";
		}
		String tableName = className.substring(0, pos[1]);
		for (int k = 1; k < j; k++) {
			if (pos[k + 1] > 0) {
				tableName += TABLE_SEPARATE
						+ className.substring(pos[k], pos[k + 1]);
			} else {
				tableName += TABLE_SEPARATE + className.substring(pos[k]);
			}
		}
		return tableName;
	}
}
